package com.tcoiss.datafactory.util;

import com.tcoiss.common.core.exception.CustomException;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.common.redis.service.RedisService;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class InsertRunable implements Runnable {

    private int num;
    private CountDownLatch end;
    private CountDownLatch begin;
    private List<Object[]> list;

    private JdbcTemplate jdbcTemplate;

    private RedisService redisService;

    private String insertSql;


    public InsertRunable(){

    }
    // 至少num至少从1开始
    public InsertRunable(JdbcTemplate jdbcTemplate,RedisService redisService,String sql ,List<Object[]> list, CountDownLatch begin, CountDownLatch end,int num){
        this.end=end;
        this.begin=begin;
        this.jdbcTemplate = jdbcTemplate;
        this.redisService = redisService;
        this.insertSql = sql;
        this.list = list;
        this.num = num;
    }

    @Override
    public void run() {
        Long startTime = System.currentTimeMillis();
        int[] intsertnum = new int[0];
        try {
//            for (int i = 0; i < list.size(); i++) {
//
//            }
            //这里还要说一下，，由于在实质项目中，当处理的数据存在等待超时和出错会使线程一直处于等待状态
            //这里只是处理简单的，
            //分批 批量插入
            intsertnum = jdbcTemplate.batchUpdate(insertSql,list);
            //执行完让线程直接进入等待
            begin.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //这里要主要了，当一个线程执行完 了计数要减一不然这个线程会被一直挂起
            // ，end.countDown()，这个方法就是直接把计数器减一的
            end.countDown();
        }
        Long endTime = System.currentTimeMillis();
        System.out.println("完成第"+num+"次"+intsertnum.length+"数据插入,花费: "+(endTime-startTime)/1000+"s");
    }
}

